from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL
import bcrypt  # 用于密码哈希，生产环境中考虑使用像Werkzeug这样更强大的库

app = Flask(__name__, static_url_path='/static')
# MySQL配置
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'  # 更换为你的MySQL用户名
app.config['MYSQL_PASSWORD'] = 'root'  # 更换为你的MySQL密码
app.config['MYSQL_DB'] = 'fwj'  # 更换为你的MySQL数据库名

mysql = MySQL(app)

# 注册新用户的路由
@app.route('/register', methods=['POST'])
def register():
    username = request.form['username']
    password = request.form['password']

    # 对密码进行哈希处理（使用bcrypt哈希）
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

    # 检查用户名是否已存在
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users WHERE username = %s", (username,))
    user = cur.fetchone()
    cur.close()

    if user:
        return jsonify({'message': '用户名已存在'}), 400

    # 将新用户插入数据库
    cur = mysql.connection.cursor()
    cur.execute("INSERT INTO users (username, password_hash) VALUES (%s, %s)", (username, hashed_password))
    mysql.connection.commit()
    cur.close()

    return jsonify({'message': '用户注册成功'}), 200

# 检查用户名是否存在的路由
@app.route('/username', methods=['POST'])
def check_username():
    username = request.form['username']
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users WHERE username = %s", (username,))
    user = cur.fetchone()
    cur.close()

    if user:
        return jsonify({'exists': True}), 200
    else:
        return jsonify({'exists': False}), 200

# 用户登录的路由
@app.route('/login', methods=['POST'])
def login():
    username = request.json['username']
    password = request.json['password']

    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users WHERE username = %s", (username,))
    user = cur.fetchone()
    cur.close()

    if user:
        stored_password = user[2]  # 假设密码哈希存储在第三列
        if bcrypt.checkpw(password.encode('utf-8'), stored_password.encode('utf-8')):
            return jsonify({'message': '登录成功'}), 200
        else:
            return jsonify({'message': '密码错误'}), 401
    else:
        return jsonify({'message': '用户不存在'}), 404

if __name__ == '__main__':
    app.run(debug=True)
